package socket

import (
	"encoding/json"
	"errors"
	"got/cache"
	"net"
	"sync"
	"time"
)

//-----------------------------------------------------------------
//socket连接
type Conn struct {
	id             int64        //当前连接的编号
	LastAccessTime time.Time    //最后访问时间
	conn           net.Conn     //net默认的连接对象
	Cache          *cache.Cache //继承内存缓存作为保存常用数据
	RemoteCall     *RemoteCall  //远程调用
	sync.Mutex                  //小锁
}

func newConn(c net.Conn) *Conn {
	o := new(Conn)
	o.conn = c //保存连接对象
	o.Cache = cache.NewCache(0)
	o.RemoteCall = newRemoteCall(o)
	return o
}

//连接编号
func (this *Conn) GetId() int64 {
	return this.id
}

//读取通讯数据(加个锁，让它有点次序)
//输入：rl=读取初始数据长度
func (this *Conn) Read() ([]byte, error) {
	buf := make([]byte, 65535)
	l, err := this.conn.Read(buf)
	if err != nil {
		return nil, err
	}
	return buf[:l], nil
}

//写入
func (this *Conn) Write(bt []byte) (n int, err error) {
	return this.conn.Write(bt)
}

//关闭连接
func (this *Conn) Close() error {
	if this.conn == nil {
		return errors.New("not connected.")
	}
	return this.conn.Close()
}

//本地服务地址
func (this *Conn) LocalAddr() net.Addr {
	return this.conn.LocalAddr()
}

//请求的来路
func (this *Conn) RemoteAddr() net.Addr {
	return this.conn.RemoteAddr()
}

//超时时间
func (this *Conn) SetDeadline(t time.Time) error {
	return this.conn.SetDeadline(t)
}

//读超时时间
func (this *Conn) SetReadDeadline(t time.Time) error {
	return this.conn.SetReadDeadline(t)
}

//写超时时间
func (this *Conn) SetWriteDeadline(t time.Time) error {
	return this.conn.SetWriteDeadline(t)
}

//将数据转换格式,并加密
func (this *Conn) Unmarshal(data []byte, v interface{}) error {
	//data = EasyEncode(data)
	return json.Unmarshal(data, v)
}

//序列化，并加密
func (this *Conn) Marshal(v interface{}) []byte {
	bt, err := json.Marshal(v)
	if err != nil {
		bt = []byte{}
	}
	//bt = EasyEncode(bt)
	return bt
}
